package com.jhonatan.sitcom.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;


public class JSONParser {
	static JSONArray jarray =null;
	public JSONParser(){
		
		
	}
	public JSONArray getJSONfromURL(String url){
		
		System.out.println("--###>Peticion Comenzada---------------");
		StringBuilder builder = new StringBuilder();
		HttpClient client = new DefaultHttpClient();
		HttpGet getData = new HttpGet(url);
		
			try{
				HttpResponse response = client.execute(getData);
				StatusLine statusLine = response.getStatusLine();
				int statusCode= statusLine.getStatusCode();
				if(statusCode==200){
					HttpEntity entity = response.getEntity();
					InputStream content = entity.getContent();
					BufferedReader reader = new BufferedReader(new InputStreamReader(content));
					String line;
					while((line=reader.readLine()) !=null){
						builder.append(line);
						
					}
				}
				System.out.println("--###>Peticion Exitosa---------------");
		}catch(ClientProtocolException e) {	}
		catch(IOException e) {	}

			
		//intenta convertir a string
			try {
				if(builder!=null){
				jarray = new JSONArray(builder.toString());

				System.out.println("--###>Conversion a Array---------------");
				}else{					
					jarray=null;
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				System.out.println("--###>Conversion a Array Erronea---------------");				
				e.printStackTrace();
				jarray=null;
			}
				
		return jarray;
	}
	

}
